import React, { Fragment } from 'react'
import { View, StyleSheet, ImageBackground, Text, ScrollView } from 'react-native'
import { ScaleS, ScaleT, ONE_PIXEL } from 'src/utils/ScreenUtil'
import BasePage from 'src/pageP/base/base-page/index'
import NextButton from 'src/components/button/NextButton'
import CustomButton from 'src/components/button/CustomButton'
import CustomImage from 'src/components/image/CustomImage'
import ActionSheetModal from 'src/components/modal/ActionSheetModal'
import { openAlums, openCamera, multipleAlums } from 'src/utils/ImagePickerUtil'
import { CommonToast, ShowLoading, DismissLoading } from 'src/utils/ToastUtil'
import { uploadImage, insertCompany } from 'src/utils/RequestAPI'
import { ServiceTelephone } from 'src/config/index'
import { CustomCallPhone } from 'src/utils/PermissionsUtil'

import { connect } from 'react-redux'
import { DO_REQUEST_MAIN_PAGE_B_ACTION } from 'src/pageB/main/main-page/store/action'
import { UPDATE_USERINFO_ACTION } from 'src/store/actions/userinfo'

// 发送行为
const mapDispatchToProps = dispatch => ({
  updateUserInfo (payload) {
    dispatch(UPDATE_USERINFO_ACTION(payload))
  },
  doRequestUserCompanyApplyApply (payload) {
    const promise = DO_REQUEST_MAIN_PAGE_B_ACTION(payload)
    dispatch(promise)
    return promise.payload
  }
})

@connect(
  ({ userinfo, BMineCenterStore }) => ({
    userId: userinfo.B.userId,
    haveCompanyApply: BMineCenterStore.haveCompanyApply
  }),
  mapDispatchToProps
)
class BCompanyApplyLicence extends BasePage {
  constructor (props) {
    super(props)
    this.state = {
      header: {},
      imageSelectShow: false,
      moreSelectShow: false,
      mime: ''
    }
  }

  selectArrImage = [
    {
      label: '相册上传'
    }
  ]

  selectArrMore = [
    {
      value: 0,
      label: '切换为求职者'
    }
  ]

  configState = () => {
    const {
      navigation: {
        state: { params }
      },
      haveCompanyApply
    } = this.props
    let creatCompany
    let companyName
    let licenseImg
    let createdTip
    let nextBtnText
    let nextBtnTextEnable
    this.selectArrMore = [
      {
        value: 0,
        label: '切换为求职者'
      }
    ]
    if (params && !params.disable) {
      creatCompany = true
      companyName = params.companyName
      licenseImg = ''
      createdTip = null
      nextBtnText = '申请创建'
      nextBtnTextEnable = false
    } else if (haveCompanyApply.type === 'company') {
      creatCompany = false
      companyName = haveCompanyApply.companyName
      licenseImg = haveCompanyApply.licenseUrl
      const {
        haveCompanyApply: { checkStatus }
      } = this.props
      switch (checkStatus) {
        case 0:
          creatCompany = true
          createdTip = null
          nextBtnText = '审核未通过，重新申请'
          nextBtnTextEnable = true
          this.selectArrMore = [
            {
              value: 1,
              label: '更换企业'
            },
            {
              value: 0,
              label: '切换为求职者'
            }
          ]
          break
        case 1:
          createdTip = '您的申请已通过审核'
          nextBtnText = ' 审核通过，去招人'
          nextBtnTextEnable = true
          this.goBack()
          break
        case 2:
          createdTip = '30分钟内审核结束，请耐心等待'
          nextBtnText = ' 审核中...'
          nextBtnTextEnable = false
          this.refreshApplyState()
          break
        default:
          break
      }
    }
    this.setState({
      creatCompany,
      companyName,
      licenseImg,
      createdTip,
      nextBtnText,
      nextBtnTextEnable
    })
    return {
      creatCompany,
      companyName,
      licenseImg,
      createdTip,
      nextBtnText,
      nextBtnTextEnable
    }
  }

  componentDidMount () {
    const {
      navigation: {
        state: { params }
      }
    } = this.props
    if (!params) {
      this.refreshApplyState(0)
    }
    this.configState()
  }

  componentWillUnmount () {
    super.componentWillUnmount()
    this.clearRefreshTimer()
  }

  refreshApplyState = (dealy = 15000) => {
    this.clearRefreshTimer()
    this.refreshTimer = setTimeout(() => {
      const {
        userId
      } = this.props
      this.props.doRequestUserCompanyApplyApply({ userId }).finally(() => {
        this.configState()
      })
    }, dealy)
  }

  clearRefreshTimer = () => {
    this.refreshTimer && clearTimeout(this.refreshTimer)
    this.refreshTimer = null
  }

  childRender () {
    const {
      imageSelectShow,
      moreSelectShow,
      creatCompany,
      companyName,
      licenseImg,
      createdTip,
      nextBtnText,
      nextBtnTextEnable
    } = this.state
    console.log(this.state)
    return (
      <Fragment>
        <ScrollView
          style={styles.container}
          keyboardShouldPersistTaps="handled"
        >
          <Text style={styles.companyName}>{companyName}</Text>
          <View style={styles.licenceWrap}>
            {creatCompany && !licenseImg && (
              <View style={styles.licencePlaceHolderWrap}>
                <CustomButton
                  style={styles.licenceBtn}
                  onPress={this._showImageActionSheetModal}
                >
                  <ImageBackground
                    style={styles.licencePlaceHolder}
                    source={require('@/imgC/company/icencePlaceHolder.png')}
                  >
                    <CustomImage
                      style={styles.licenceAdd}
                      source={require('@/imgC/company/add_black_34.png')}
                    />
                  </ImageBackground>
                </CustomButton>
                <Text style={styles.licenceTip}>
                  请上传营业执照复印件加盖公章
                </Text>
              </View>
            )}
            {!!licenseImg && (
              <CustomImage
                style={styles.licenceImg}
                source={{ uri: licenseImg }}
              />
            )}
          </View>
          {!creatCompany && <Text style={styles.createdTip}>{createdTip}</Text>}
          {creatCompany && nextBtnTextEnable && (
            <CustomButton
              style={styles.reUploadBtn}
              onPress={this._showImageActionSheetModal}
            >
              <CustomImage
                style={styles.reUploadImg}
                source={require('@/imgC/company/add_black_34.png')}
              />
              <Text style={styles.reUploadText}>重新上传</Text>
            </CustomButton>
          )}
        </ScrollView>
        <View style={styles.bottomWrap}>
          <View style={styles.tipWrap}>
            <Text style={styles.tipText}>紧急招聘请联系客服热线：</Text>
            <CustomButton onPress={this.callPhone}>
              <Text
                style={[
                  styles.tipText,
                  { textDecorationLine: 'underline', color: '#FFC200' }
                ]}
              >
                {ServiceTelephone}
              </Text>
            </CustomButton>
          </View>
          <NextButton
            style={styles.nextButton}
            title={nextBtnText}
            enable={nextBtnTextEnable}
            onPress={this._nextBtnClick}
          />
        </View>
        <ActionSheetModal
          visible={imageSelectShow}
          onCancel={this._imageActionSheetModalCancel}
          selectClick={this._imageActionSheetModalClick}
          onModalHide={this._imageActionSheetModalHide}
          titleText={'添加照片'}
          selectArr={this.selectArrImage}
        />
        <ActionSheetModal
          visible={moreSelectShow}
          onCancel={this._moreActionSheetModalCancel}
          selectClick={this._moreActionSheetModalClick}
          onModalHide={this._moreActionSheetModalHide}
          titleText={'更多'}
          selectArr={this.selectArrMore}
        />
      </Fragment>
    )
  }

  renderNavigationBarChild () {
    return (
      <CustomButton
        style={styles.moreBtn}
        onPress={this._showMoreActionSheetModal}
      >
        <Text style={styles.moreText}>更多</Text>
      </CustomButton>
    )
  }

  /* 图片选择 begin */
  _showImageActionSheetModal = () => {
    this.toggleModal('imageSelectShow', true)
  }

  _imageActionSheetModalCancel = () => {
    this.toggleModal('imageSelectShow', false)
  }

  _imageActionSheetModalClick = () => {
    this.toggleModal('imageSelectShow', false)
  }

  _imageActionSheetModalHide = index => {
    if (!index) {
      return
    }
    switch (index - 1) {
      case 0:
        this._albumsSelect()
        break
      case 1:
        this._cameraSelect()
        break
      default:
        break
    }
  }

  _albumsSelect = () => {
    multipleAlums({
      maxFiles: 1,
      compressImageMaxWidth: 1500,
      compressImageMaxHeight: 1500
    })
      .then(([image]) => {
        this.setState({
          nextBtnTextEnable: true,
          licenseImg: image.imgPath,
          mime: image.mime
        })
      })
      .catch(error => {
        console.log(error)
        error && CommonToast(error.message)
      })
      .done(() => {
        console.log('done')
        this._imageActionSheetModalCancel()
      })
  }

  _cameraSelect = () => {
    openCamera({ width: 1500, height: 1500 })
      .then(image => {
        this.setState({
          nextBtnTextEnable: true,
          licenseImg: image.imgPath,
          mime: image.mime
        })
      })
      .catch(error => {
        console.log(error)
        CommonToast(error.message)
      })
      .done(() => {
        console.log('done')
        this._imageActionSheetModalCancel()
      })
  }

  /* 图片选择 end */
  toggleModal = (selectShow, value) => {
    this.setState({
      [selectShow]: value
    })
  }

  /* more选择 begin */
  _showMoreActionSheetModal = () => {
    this.toggleModal('moreSelectShow', true)
  }

  _moreActionSheetModalCancel = () => {
    this.toggleModal('moreSelectShow', false)
  }

  _moreActionSheetModalClick = () => {
    this.toggleModal('moreSelectShow', false)
  }

  _moreActionSheetModalHide = index => {
    if (!index) {
      return
    }
    const { navigation, updateUserInfo } = this.props
    switch (this.selectArrMore[index - 1].value) {
      case 0:
        console.log('切换为求职者')
        updateUserInfo({
          role: 'C'
        })
        navigation.navigate('CMainNavigator')
        break
      case 1:
        navigation.replace('BCompanyApplyName')
        break
      default:
        break
    }
  }

  /* more选择 end */
  _nextBtnClick = () => {
    const { creatCompany, licenseImg: uri, mime } = this.state
    if (creatCompany) {
      if (!uri) {
        CommonToast(`请上传营业执照复印件加盖公章`)
      }
      ShowLoading()
      new Promise((resolve, reject) => {
        if (uri.startsWith('file://')) {
          // 本地上传
          uploadImage({ params: { uri, mime, type: 'company' } })
            .then(res => {
              resolve({
                licenseUrl: res.data
              })
            })
            .catch(error => {
              reject(error)
            })
        } else {
          // 网络图片
          resolve({
            licenseUrl: uri
          })
        }
      })
        .then(({ licenseUrl }) => {
          const {
            navigation: {
              state: { params }
            },
            haveCompanyApply,
            userId
          } = this.props
          let companyParams
          if (
            params &&
            !params.disable &&
            params.companyName &&
            params.tianYanChaId
          ) {
            companyParams = {
              userId,
              licenseUrl,
              companyName: params.companyName,
              tianYanChaId: params.tianYanChaId,
              upstreamAppName: 'ZHI_CHU',
              applyAddress: '上海'
            }
            const { companyId, type } = haveCompanyApply
            if (companyId && type === 'company') {
              // 再次申请带上companyId
              companyParams.companyId = companyId
            }
          } else {
            const { companyName, companyId, tianYanChaId } = haveCompanyApply
            companyParams = {
              userId,
              licenseUrl,
              companyName,
              companyId,
              tianYanChaId,
              upstreamAppName: 'ZHI_CHU',
              applyAddress: '上海'
            }
          }
          return insertCompany({ params: companyParams })
        })
        .then(res => {
          return this.props.doRequestUserCompanyApplyApply()
        })
        .then(res => {
          this.props.navigation.setParams({ disable: true })
          const {
            creatCompany,
            companyName,
            licenseImg,
            createdTip,
            nextBtnText,
            nextBtnTextEnable
          } = this.configState()
          this.setState({
            creatCompany,
            companyName,
            licenseImg,
            createdTip,
            nextBtnText,
            nextBtnTextEnable
          })
        })
        .finally(() => {
          DismissLoading()
        })
    }
  }

  callPhone = () => {
    CustomCallPhone(ServiceTelephone)
  }
  // goBack = () => {
  //   debugger
  //   console.log(this.props.navigation)
  // }
}
export default BCompanyApplyLicence
const styles = StyleSheet.create({
  container: {
    flex: 1,
    marginBottom: ScaleS(106),
    marginHorizontal: ScaleS(20)
  },
  moreBtn: {
    alignSelf: 'flex-end',
    marginRight: ScaleS(20),
    width: ScaleS(58),
    height: ScaleS(28),
    borderRadius: ScaleS(14),
    borderStyle: 'solid',
    borderColor: '#000000',
    borderWidth: ONE_PIXEL,
    justifyContent: 'center',
    alignItems: 'center'
  },
  moreText: {
    color: '#000000',
    fontSize: ScaleT(12),
    fontWeight: '600'
  },
  companyName: {
    marginVertical: ScaleS(10),
    fontSize: ScaleT(27),
    fontWeight: '500',
    color: '#000000',
    lineHeight: ScaleS(47)
  },

  licenceWrap: {
    marginTop: ScaleS(20),
    height: ScaleS(280),
    borderRadius: ScaleS(5),
    backgroundColor: '#F7F7F7',
    alignItems: 'center',
    justifyContent: 'center'
  },
  licencePlaceHolderWrap: {
    alignItems: 'center'
  },
  licenceBtn: {
    marginTop: ScaleS(15)
  },
  licencePlaceHolder: {
    width: ScaleS(152),
    height: ScaleS(152),
    justifyContent: 'center',
    alignItems: 'center'
  },
  licenceAdd: {
    width: ScaleS(34),
    height: ScaleS(34)
  },
  licenceTip: {
    marginTop: ScaleS(26),
    fontSize: ScaleT(12),
    lineHeight: ScaleS(28),
    fontWeight: '400',
    color: '#444444'
  },
  licenceImg: {
    height: ScaleS(232),
    width: ScaleS(232),
    resizeMode: 'contain'
  },
  createdTip: {
    alignSelf: 'center',
    marginTop: 30,
    fontSize: ScaleT(14),
    color: '#444444',
    lineHeight: ScaleS(28)
  },
  reUploadBtn: {
    alignSelf: 'center',
    marginTop: ScaleS(27),
    width: ScaleS(109),
    height: ScaleS(35),
    borderRadius: ScaleS(19),
    borderWidth: ONE_PIXEL,
    borderStyle: 'solid',
    borderColor: '#E5E5E5',
    paddingHorizontal: ScaleS(15),
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center'
  },
  reUploadImg: {
    width: ScaleS(15)
  },
  reUploadText: {
    fontSize: ScaleT(14),
    color: '#000',
    fontWeight: '400'
  },
  bottomWrap: {
    position: 'absolute',
    bottom: 0,
    left: 0,
    width: '100%',
    height: ScaleS(116),
    justifyContent: 'center',
    alignItems: 'center'
  },
  tipWrap: {
    height: ScaleS(25),
    flexDirection: 'row',
    alignItems: 'center'
  },
  tipText: {
    fontSize: ScaleT(13),
    fontWeight: '400',
    color: '#CCCCCC'
  },
  nextButton: {
    marginTop: ScaleS(10)
  }
})
